﻿/*******************************************************************************
 * AAEngine
 * Copyright (c) 2010 Mike Jarosch
 *
 * This file is licensed under the terms of the MIT license, which is included
 * in the "MIT License.txt" file at the root directory of this SDK.
 ******************************************************************************/

using Microsoft.Xna.Framework;
using AAEngine.Engine;
using AAEngine.Engine.Core;
using AAEngine.Engine.Entities;

namespace AAEngine.Rendering2D
{
    public class TrackingCamera2D : Camera2D, IAnimatedObject
    {
        private IEntity _trackedObject;
        private Vector2 _trackedOffset;
        private Box? _trackLimit;

        public IEntity TrackedObject
        {
            get { return _trackedObject; }
            set
            {
                _trackedObject = value;

                if (IsRegistered)
                {
                    UpdatePosition();
                }
            }
        }

        public Vector2 TrackedOffset
        {
            get { return _trackedOffset; }
            set { _trackedOffset = value; }
        }

        public PropertyReference TrackLimitProperty { get; set; }

        public Box? TrackLimit
        {
            get { return _trackLimit; }
            set { _trackLimit = value; }
        }

        public override void OnAdd()
        {
            base.OnAdd();

            AAGame.ProcessManager.AddAnimatedObject(this, -10);
        }

        public override void OnRemove()
        {
            AAGame.ProcessManager.RemoveAnimatedObject(this);

            base.OnRemove();
        }

        public void OnFrame(float delta)
        {
            UpdatePosition();
        }

        protected void UpdatePosition()
        {
            if (_trackedObject != null)
            {
                ISpatialObject2D spatial = (ISpatialObject2D)_trackedObject.LookupComponentByName("Spatial");
                Position = spatial.WorldExtents.Center + _trackedOffset;
            }

            if (TrackLimitProperty != null)
            {
                Box limit = (Box)Owner.GetProperty(TrackLimitProperty);
                Position = new Vector2(MathHelper.Clamp(Position.X, limit.Left, limit.Right),
                    MathHelper.Clamp(Position.Y, limit.Top, limit.Bottom));
            }
        }
    }
}
